﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using hachiModel;

namespace Hachi.Controllers
{
    public class ProductsController : BaseController
    {
        public ProductsController()
        {
        }

        public List<PR_Product> getListProductInType(int TypeID)
        {
            PR_ProductType t = new PR_ProductType();
            t = en.PR_ProductType.Where(d => d.TypeID == TypeID).FirstOrDefault();
            if (!t.PR_Product.IsLoaded)
            {
                t.PR_Product.Load();
            }
            return t.PR_Product.Where(d => d.IsApproved == true && d.IsDeleted == false && d.Quantity > 0).OrderBy(o => o.SortOrder).ThenByDescending(o => o.CreatedDate).ToList();
        }
        public List<PR_Product> getListProductInType(int TypeID, int Take, int Skip, decimal FromPrice, decimal ToPrice)
        {
            PR_ProductType t = new PR_ProductType();
            t = en.PR_ProductType.Where(d => d.TypeID == TypeID).FirstOrDefault();
            if (!t.PR_Product.IsLoaded)
            {
                t.PR_Product.Load();
            }
            return t.PR_Product.Where(d => d.IsApproved == true && d.IsDeleted == false && d.Quantity > 0&&(FromPrice<=d.Price&&d.Price<=ToPrice)).Skip(Skip).Take(Take).OrderBy(o => o.SortOrder).ThenByDescending(o => o.CreatedDate).ToList();
        }
        public int ProductInTypeProductsCount(int TypeID, decimal FromPrice, decimal ToPrice)
        {
            PR_ProductType t = new PR_ProductType();
            t = en.PR_ProductType.Where(d => d.TypeID == TypeID).FirstOrDefault();
            if (!t.PR_Product.IsLoaded)
            {
                t.PR_Product.Load();
            }
            return t.PR_Product.Where(d => d.IsApproved == true && d.IsDeleted == false && d.Quantity > 0 && (FromPrice <= d.Price && d.Price <= ToPrice)).Count();

        }

        public List<PR_Product> ProductTypeGetProducts(int TypeID, int Take, int Skip, decimal FromPrice, decimal ToPrice)
        {
            PR_ProductType t = new PR_ProductType();
            t = en.PR_ProductType.Where(d => d.TypeID == TypeID).FirstOrDefault();
            if (!t.PR_Product.IsLoaded)
            {
                t.PR_Product.Load();
            }
            return t.PR_Product.Where(d => d.IsApproved == true && d.IsDeleted == false && d.Quantity > 0 && (FromPrice <= d.Price && d.Price <= ToPrice)).OrderBy(o=>o.SortOrder).Skip(Skip).Take(Take).ToList();

        }

        public PR_Product getProduct(int ProductID)
        {
            PR_Product p = en.PR_Product.Where(d => d.ProductID == ProductID && d.IsApproved && d.IsDeleted == false).FirstOrDefault();
            return p;
        }
        public long HitProduct(int ProductID)
        {
            PR_Product p = en.PR_Product.Where(d => d.ProductID == ProductID).FirstOrDefault();
            p.Hit++;
            en.SaveChanges();
            return p.Hit;
        }
        public PR_ProductDetail getProductDetail(int ProductID)
        {
            return en.PR_ProductDetail.Where(d => d.ProductID == ProductID).FirstOrDefault();
        }
        public PR_ProductDetail getProductDetailToShow(PR_Product p, string lang)
        {
            PR_ProductDetail pd = p.PR_ProductDetail.Where(d => d.Language == lang).FirstOrDefault();
            if (pd == null)
            {
                pd = new PR_ProductDetail();
            }
            return pd;
        }
        
        public bool IsInType(int ProductID, int TypeID)
        {
            PR_Product p = en.PR_Product.Where(d => d.ProductID == ProductID).FirstOrDefault();
            if (p != null && p.PR_ProductType.Where(d => d.TypeID == TypeID).Count() > 0)
                return true;
            else
                return false;
        }
        public bool IsTopicalProduct(int ProductID)
        {
            PR_Product p = en.PR_Product.Where(d => d.ProductID == ProductID).FirstOrDefault();
            if (p != null && p.CS_Promotion.Where(d => d.PromotionID == 1).Count() > 0)
                return true;
            else
                return false;
        }
        public bool IsPromotionProduct(int ProductID)
        {
            PR_Product p = en.PR_Product.Where(d => d.ProductID == ProductID).FirstOrDefault();
            if (p != null && p.CS_Promotion.Where(d => d.PromotionID != 1).Count() > 0)
                return true;
            else
                return false;
        }

        public string BuildAlias()
        {
            string log = "";
            DateTime start = DateTime.Now;
            CategoriesController catctr = new CategoriesController();
            foreach (var c in en.PR_Category.Where(d => d.IsDeleted == false))
            {
                foreach (var cd in c.PR_CategoryDetail.Where(d => d.Alias != null && d.Language != null))
                {
                    foreach (var p in c.PR_Product.Where(d => d.IsDeleted == false))
                    {
                        foreach (var pd in p.PR_ProductDetail.Where(d => d.Language == cd.Language))
                        {
                            try
                            {
                                if (pd.Language == "ja-JP")
                                    pd.Alias = cd.Alias + "⁄" + pd.ProductName.Trim().Replace(" ", "-") + "-" + p.ProductID.ToString() + ".html";
                                else
                                    pd.Alias = cd.Alias + "⁄" + StringUtil.RemoveVietSignSpecialCharAndSpaceChar(pd.ProductName) + "-" + p.ProductID.ToString() + ".html";
                            }
                            catch (Exception)
                            {
                                log += p.CategoryID + "/" + cd.CategoryName + "/" + p.ProductID + "/" + pd.ProductName + "/" + pd.Language + Environment.NewLine;
                                continue;
                            }
                        }
                    }
                }
            }

            en.SaveChanges();
            DateTime end = DateTime.Now;
            return (log == "" ? "done" : log) + " | " + (end - start).TotalSeconds.ToString();

        }

        public List<PR_Product> GetProductsByCategoryID(int CategoryID, int Take, int Skip)
        {
            PR_Category c = en.PR_Category.Where(d => d.CategoryID == CategoryID).FirstOrDefault();
            if (c.ParentID != null)
            {
                return en.PR_Product.Where(d => d.CategoryID == CategoryID && d.IsDeleted == false && d.IsApproved == true && d.Quantity > 0).OrderBy(o => o.SortOrder).Skip(Skip).Take(Take).ToList();
            }
            else
            {
                List<int> idl = new List<int>();
                foreach (PR_Category item in c.PR_Category1.ToList())
                    idl.Add(item.CategoryID);
                return en.PR_Product.Where(d =>idl.Contains(d.CategoryID) && d.IsDeleted == false && d.IsApproved == true && d.Quantity > 0).OrderBy(o => o.SortOrder).Skip(Skip).Take(Take).ToList();
            }

           
        }
        public List<PR_Product> GetProductsByCategoryID(string Lang, int CategoryID, int Take, int Skip, decimal FromPrice, decimal ToPrice)
        {
            
            PR_Category c = en.PR_Category.Where(d=>d.CategoryID==CategoryID).FirstOrDefault();
            if (c.ParentID != null)
            {
                return en.PR_Product.Where(
                d => d.CategoryID == CategoryID
                && d.PR_ProductDetail.Where(dt => dt.Language == Lang).Count() > 0
                && d.IsDeleted == false
                && d.IsApproved == true && d.Quantity > 0
                && d.Price >= FromPrice && d.Price <= ToPrice
                )
                .OrderBy(o => o.SortOrder).Skip(Skip).Take(Take).ToList();
            }
            else
            {
                List<int> idl = new List<int>();

                foreach (PR_Category item in c.PR_Category1.ToList())
                    idl.Add(item.CategoryID);

                return en.PR_Product.Where(
                d => idl.Contains(d.CategoryID)
                && d.PR_ProductDetail.Where(dt => dt.Language == Lang).Count() > 0
                && d.IsDeleted == false
                && d.IsApproved == true && d.Quantity > 0
                && d.Price >= FromPrice && d.Price <= ToPrice
                )
                .OrderBy(o => o.SortOrder).Skip(Skip).Take(Take).ToList();
            }
            
        }
        public List<PR_ProductImages> GetProductImageByProduct(int pProductID)
        {
            return getProduct(pProductID).PR_ProductImages.ToList();
        }
        public List<PR_ProductImages> GetProductImageByProduct(PR_Product pProduct)
        {
            if (!pProduct.PR_ProductImages.IsLoaded)
            {
                pProduct.PR_ProductImages.Load();
            }
            return pProduct.PR_ProductImages.ToList();
        }
        public List<NW_NewsDetail> GetProductNews(PR_Product pProduct, string lang)
        {
            List<NW_NewsDetail> ndl = new List<NW_NewsDetail>(); pProduct.NW_News.Load();
            foreach (NW_News item in pProduct.NW_News.Where(d => d.IsApproved && d.IsDeleted == false).OrderBy(o => o.SortOrder).ToList())
            {
                List<NW_NewsDetail> nd = NewsDetail(item.NewsID, lang);
                if (nd.Count > 0)
                    ndl.AddRange(nd);
            }
            return ndl;
        }
        public List<NW_NewsDetail> NewsDetail(int pNewsID, string lang)
        {
            return en.NW_NewsDetail.Where(d => d.NewsID == pNewsID && d.Language == lang).ToList();
        }
        public List<PR_ProductComment> GetProductComment(int pProductID)
        {
            PR_Product p = getProduct(pProductID);
            if (p != null)
                return p.PR_ProductComment.Where(d => d.IsApproved && d.IsDeleted == false).ToList();
            else
                return null;
        }
        public string PostProductComment(int pProductID, string pUserName, string pComment, int Vote)
        {
            try
            {
                PR_ProductComment c = new PR_ProductComment();
                c.ProductID = pProductID;
                c.Comment = pComment;
                c.UserName = pUserName;
                c.Vote = Vote;
                c.ModifiedDate = DateTime.Now;
                c.ModifiedBy = pUserName;
                c.Title = "";
                en.AddToPR_ProductComment(c);
                en.SaveChanges();
                return "Posted";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public int CountPromotions()
        {
            DateTime tod = DateTime.Now;
            return en.CS_Promotion.Where(d => d.IsApproved && d.IsDeleted == false && (d.StartDate <= tod && tod <= d.EndDate) && d.PR_Product.Count > 0).Count();
        }
        public List<CS_Promotion> GetPromotions(int Take, int Skip)
        {
            DateTime tod = DateTime.Now;
            return en.CS_Promotion.Where(d => d.IsApproved && !d.IsDeleted && (d.StartDate <= tod && d.EndDate >= tod) &&d.PR_Product.Count>0).OrderBy(o => o.SortOrder).Skip(Skip).Take(Take).ToList();
        }
        public CS_Promotion GetPromotionDetail(int pPromotionID)
        {
            return en.CS_Promotion.Where(d => d.PromotionID == pPromotionID).FirstOrDefault();
        }
        public CS_PromotionDetail GetPromotionDetail(CS_Promotion pPromotion, string Lang)
        {
            CS_PromotionDetail pd = pPromotion.CS_PromotionDetail.Where(d => d.Language == Lang).FirstOrDefault();
            if (pd==null)
            {
                pd = new CS_PromotionDetail();
            }
            return pd;
        }
        public List<PR_Product> GetPromotionProducts(string Lang, int pPromotionID, int Take, int Skip, decimal FromPrice, decimal ToPrice)
        {
            CS_Promotion promotionItem = GetPromotionDetail(pPromotionID);
            return promotionItem.PR_Product.Where(
                d => d.PR_ProductDetail.Where(dt => dt.Language == Lang).Count() > 0
                && d.IsDeleted == false
                && d.IsApproved == true && d.Quantity > 0
                && d.Price >= FromPrice && d.Price <= ToPrice
                )
                .OrderBy(o => o.SortOrder).Skip(Skip).Take(Take).ToList();
        }
        public List<PR_Product> GetTop12PromotionProducts(string Lang)
        {
            
            return en.PR_Product.Where(
                d => d.CS_Promotion.Count>0
                && d.PR_ProductDetail.Where(dt => dt.Language == Lang).Count() > 0
                && d.IsDeleted == false
                && d.IsApproved == true && d.Quantity > 0
                )
                .OrderBy(o => o.SortOrder).Skip(0).Take(12).ToList();
        }
        
        public int PromotionProductsCount(string Lang, int pPromotionID, decimal FromPrice, decimal ToPrice)
        {
            CS_Promotion promotionItem = GetPromotionDetail(pPromotionID);
            return promotionItem.PR_Product.Where(
                d => d.PR_ProductDetail.Where(dt => dt.Language == Lang).Count() > 0
                && d.IsDeleted == false
                && d.IsApproved == true && d.Quantity > 0
                && d.Price >= FromPrice && d.Price <= ToPrice
                ).Count();
        }


        public List<PR_Product> SearchGetProducts(string Key, int Take, int Skip, decimal FromPrice, decimal ToPrice)
        {
            int k = 0;
            string alias = StringUtil.RemoveVietSignSpecialCharAndSpaceChar(Key);
            int.TryParse(Key, out k);
            return en.PR_Product.Where(
                    d => d.IsApproved == true && 
                    d.IsDeleted == false && 
                    d.Quantity > 0 && 
                    (FromPrice <= d.Price && d.Price <= ToPrice)&&
                    (
                        d.ProductID==k||
                        d.DisplayCode ==Key || 
                        d.ProductCode == Key ||
                        d.PR_ProductDetail.Where
                        (
                            c=>c.ProductName.Contains(Key) ||
                            c.Summary.Contains(Key) ||
                            c.Material.Contains(Key) ||
                            c.Alias.Contains(alias) ||
                            c.Origin.Contains(Key) || 
                            c.Size.Contains(Key)||
                            c.Summary.Contains(Key)||
                            c.Uses.Contains(Key)
                        ).Count()>0
                    )
                ).OrderBy(o => o.SortOrder).Skip(Skip).Take(Take).ToList();
        }
        public int SearchProductsCount(string Key, decimal FromPrice, decimal ToPrice)
        {
            int k = 0;
            string alias = StringUtil.RemoveVietSignSpecialCharAndSpaceChar(Key);
            int.TryParse(Key, out k);
            return en.PR_Product.Where(
                    d => d.IsApproved == true &&
                    d.IsDeleted == false &&
                    d.Quantity > 0 &&
                    (FromPrice <= d.Price && d.Price <= ToPrice) &&
                    (
                        d.ProductID == k ||
                        d.DisplayCode == Key ||
                        d.ProductCode == Key ||
                        d.PR_ProductDetail.Where
                        (
                            c => c.ProductName.Contains(Key) ||
                            c.Summary.Contains(Key) ||
                            c.Material.Contains(Key) ||
                            c.Alias.Contains(alias) ||
                            c.Origin.Contains(Key) ||
                            c.Size.Contains(Key) ||
                            c.Summary.Contains(Key) ||
                            c.Uses.Contains(Key)
                        ).Count() > 0
                    )
                ).Count();
        }








    }
}